<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.goodsId" clearable class="filter-item" style="width: 160px;" :placeholder="$t('goods_list.placeholder.filter_goods_id')" />
      <el-input v-model="listQuery.goodsSn" clearable class="filter-item" style="width: 160px;" :placeholder="$t('goods_list.placeholder.filter_goods_sn')" />
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 160px;" :placeholder="$t('goods_list.placeholder.filter_name')" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('app.button.search') }}</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('app.button.create') }}</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">{{ $t('app.button.download') }}</el-button>
      <el-button class="filter-item" type="danger" icon="el-icon-delete" :disabled="batchDeleteArr.length === 0" @click="handleDeleteRows">{{ $t('app.button.batch_delete') }}</el-button>
      <el-button class="filter-item" type="warning" icon="el-icon-setting" @click="handleSecurityConfig">安全配置</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" :element-loading-text="$t('app.message.list_loading')" border fit highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" class="table-expand">
            <el-form-item :label="$t('goods_list.table.goods_sn')">
              <span>{{ props.row.goodsSn }}</span>
            </el-form-item>
            <el-form-item :label="$t('goods_list.table.gallery')">
              <el-image v-for="pic in props.row.gallery" :key="pic" :src="pic" class="gallery" :preview-src-list="props.row.gallery" style="width: 40px; height: 40px" />
            </el-form-item>
            <el-form-item :label="$t('goods_list.table.brief')">
              <span>{{ props.row.brief }}</span>
            </el-form-item>
            <el-form-item :label="$t('goods_list.table.unit')">
              <span>{{ props.row.unit }}</span>
            </el-form-item>
            <el-form-item :label="$t('goods_list.table.keywords')">
              <span>{{ props.row.keywords }}</span>
            </el-form-item>
            <el-form-item :label="$t('goods_list.table.category_id')">
              <span>{{ props.row.categoryId }}</span>
            </el-form-item>
            <el-form-item :label="$t('goods_list.table.brand_id')">
              <span>{{ props.row.brandId }}</span>
            </el-form-item>

          </el-form>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55" />
      <el-table-column align="center" :label="$t('goods_list.table.id')" prop="id" />

      <el-table-column align="center" min-width="100" :label="$t('goods_list.table.name')" prop="name" />

      <el-table-column align="center" property="iconUrl" :label="$t('goods_list.table.pic_url')">
        <template slot-scope="scope">
          <el-image :src="thumbnail(scope.row.picUrl)" :preview-src-list="toPreview(scope.row, scope.row.picUrl)" style="width: 40px; height: 40px" />
        </template>
      </el-table-column>

      <el-table-column align="center" property="iconUrl" :label="$t('goods_list.table.share_url')">
        <template slot-scope="scope">
          <img :src="scope.row.shareUrl" width="40">
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('goods_list.table.detail')" prop="detail">
        <template slot-scope="scope">
          <el-dialog :visible.sync="detailDialogVisible" :title="$t('goods_list.dialog.detail')">
            <div class="goods-detail-box" v-html="goodsDetail" />
          </el-dialog>
          <el-button type="primary" size="mini" @click="showDetail(scope.row.detail)">{{ $t('app.button.view') }}</el-button>
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('goods_list.table.counter_price')" prop="counterPrice" />

      <el-table-column align="center" :label="$t('goods_list.table.retail_price')" prop="retailPrice" />

      <el-table-column align="center" :label="$t('goods_list.table.is_new')" prop="isNew">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isNew ? 'success' : 'error' ">{{ $t(scope.row.isNew ? 'goods_list.value.is_new_true' : 'goods_list.value.is_new_false') }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('goods_list.table.is_hot')" prop="isHot">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isHot ? 'success' : 'error' ">{{ $t(scope.row.isHot ? 'goods_list.value.is_hot_true' : 'goods_list.value.is_hot_false') }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('goods_list.table.is_on_sale')" prop="isOnSale">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isOnSale ? 'success' : 'error' ">{{ $t(scope.row.isOnSale ? 'goods_list.value.is_on_sale_true' : 'goods_list.value.is_on_sale_false') }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('goods_list.table.actions')" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('app.button.edit') }}</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">{{ $t('app.button.delete') }}</el-button>
          <!-- PDF商品专用功能 -->
          <template v-if="scope.row.goodsType === 1">
            <el-button type="success" size="mini" @click="handlePreviewPdf(scope.row)">预览PDF</el-button>
            <el-button type="info" size="mini" @click="handleViewStats(scope.row)">访问统计</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-tooltip placement="top" :content="$t('app.tooltip.back_to_top')">
      <back-to-top :visibility-height="100" />
    </el-tooltip>

    <!-- PDF预览对话框 -->
    <el-dialog :visible.sync="previewDialogVisible" title="PDF预览" width="80%" top="5vh">
      <div class="pdf-preview-container">
        <div class="preview-toolbar">
          <el-button-group>
            <el-button size="small" :disabled="currentPage <= 1" @click="prevPage">上一页</el-button>
            <el-button size="small" :disabled="currentPage >= totalPages" @click="nextPage">下一页</el-button>
          </el-button-group>
          <span class="page-info">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
        </div>
        <div class="preview-content">
          <iframe v-if="previewUrl" :src="previewUrl" width="100%" height="600px" frameborder="0" />
          <div v-else class="no-preview">暂无预览</div>
        </div>
      </div>
    </el-dialog>

    <!-- 访问统计对话框 -->
    <el-dialog :visible.sync="statsDialogVisible" title="访问统计" width="60%">
      <div class="stats-container">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="stat-card">
              <h3>总访问量</h3>
              <p class="stat-number">{{ statsData.totalViews || 0 }}</p>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-card">
              <h3>今日访问</h3>
              <p class="stat-number">{{ statsData.todayViews || 0 }}</p>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-card">
              <h3>本月访问</h3>
              <p class="stat-number">{{ statsData.monthViews || 0 }}</p>
            </div>
          </el-col>
        </el-row>
        <el-table :data="statsData.recentViews || []" style="margin-top: 20px;">
          <el-table-column prop="date" label="访问时间" width="180" />
          <el-table-column prop="ip" label="访问IP" width="150" />
          <el-table-column prop="userAgent" label="用户代理" />
        </el-table>
      </div>
    </el-dialog>

    <!-- 安全配置对话框 -->
    <el-dialog :visible.sync="securityDialogVisible" title="安全配置" width="50%">
      <el-form :model="securityConfig" label-width="120px">
        <el-form-item label="启用访问控制">
          <el-switch v-model="securityConfig.enableAccessControl" />
        </el-form-item>
        <el-form-item label="允许的IP范围">
          <el-input v-model="securityConfig.allowedIpRange" placeholder="例如: 192.168.1.0/24" />
        </el-form-item>
        <el-form-item label="最大并发访问">
          <el-input-number v-model="securityConfig.maxConcurrentAccess" :min="1" :max="1000" />
        </el-form-item>
        <el-form-item label="访问频率限制">
          <el-input-number v-model="securityConfig.rateLimit" :min="1" :max="100" />
          <span style="margin-left: 10px;">次/分钟</span>
        </el-form-item>
        <el-form-item label="启用水印">
          <el-switch v-model="securityConfig.enableWatermark" />
        </el-form-item>
        <el-form-item v-if="securityConfig.enableWatermark" label="水印文本">
          <el-input v-model="securityConfig.watermarkText" placeholder="请输入水印文本" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="securityDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveSecurityConfig">保存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
  .table-expand {
    font-size: 0;
    padding-left: 60px;
  }
  .table-expand label {
    width: 100px;
    color: #99a9bf;
  }
  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
  .gallery {
    width: 80px;
    margin-right: 10px;
  }
  .goods-detail-box img {
    width: 100%;
  }

  /* PDF预览样式 */
  .pdf-preview-container {
    text-align: center;
  }
  .preview-toolbar {
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .page-info {
    font-size: 14px;
    color: #666;
  }
  .preview-content {
    border: 1px solid #ddd;
    border-radius: 4px;
  }
  .no-preview {
    height: 600px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #999;
    font-size: 16px;
  }

  /* 访问统计样式 */
  .stats-container {
    padding: 20px;
  }
  .stat-card {
    text-align: center;
    padding: 20px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background: #f9f9f9;
  }
  .stat-card h3 {
    margin: 0 0 10px 0;
    font-size: 14px;
    color: #666;
  }
  .stat-number {
    margin: 0;
    font-size: 24px;
    font-weight: bold;
    color: #409eff;
  }
</style>

<script>
import { listGoods, deleteGoods } from '@/api/goods'
import BackToTop from '@/components/BackToTop'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { thumbnail, toPreview } from '@/utils/index'

export default {
  name: 'GoodsList',
  components: { BackToTop, Pagination },
  data() {
    return {
      batchDeleteArr: [],
      thumbnail,
      toPreview,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        goodsSn: undefined,
        name: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      goodsDetail: '',
      detailDialogVisible: false,
      downloadLoading: false,
      // PDF预览相关
      previewDialogVisible: false,
      previewUrl: '',
      currentPage: 1,
      totalPages: 1,
      currentGoods: null,
      // 访问统计相关
      statsDialogVisible: false,
      statsData: {
        totalViews: 0,
        todayViews: 0,
        monthViews: 0,
        recentViews: []
      },
      // 安全配置相关
      securityDialogVisible: false,
      securityConfig: {
        enableAccessControl: false,
        allowedIpRange: '',
        maxConcurrentAccess: 100,
        rateLimit: 10,
        enableWatermark: false,
        watermarkText: ''
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listGoods(this.listQuery).then(response => {
        this.list = response.data.data.list
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCreate() {
      this.$router.push({ path: '/goods/create' })
    },
    handleUpdate(row) {
      this.$router.push({ path: '/goods/edit', query: { id: row.id }})
    },
    showDetail(detail) {
      this.goodsDetail = detail
      this.detailDialogVisible = true
    },
    handleDelete(row) {
      this.$confirm('确定删除?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        deleteGoods(row).then(response => {
          this.$notify.success({
            title: '成功',
            message: '删除成功'
          })
          this.getList()
        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
      }).catch(() => {})
    },
    handleSelectionChange(val) {
      console.log(val)
      this.batchDeleteArr = val
    },
    handleDeleteRows() {
      this.batchDeleteArr.forEach(row => this.handleDeleteEachRow(row))
      this.getList()
    },
    // PDF预览功能
    handlePreviewPdf(row) {
      this.currentGoods = row
      this.totalPages = row.pdfTotalPages || 1
      this.currentPage = 1
      this.previewUrl = this.generatePreviewUrl(row, 1)
      this.previewDialogVisible = true
    },
    generatePreviewUrl(goods, page) {
      // 生成PDF预览URL，使用pdfFileKey而不是完整的pdfFilePath
      if (goods.pdfFileKey) {
        return `${process.env.VUE_APP_BASE_API}/storage/pdf/${goods.pdfFileKey}#page=${page}`
      }
      return ''
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
        this.previewUrl = this.generatePreviewUrl(this.currentGoods, this.currentPage)
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++
        this.previewUrl = this.generatePreviewUrl(this.currentGoods, this.currentPage)
      }
    },
    // 访问统计功能
    handleViewStats(row) {
      this.statsDialogVisible = true
      this.loadStatsData(row.id)
    },
    loadStatsData(goodsId) {
      // 调用后端API获取统计数据
      this.$http.get(`/admin/goods/stats/${goodsId}`).then(response => {
        this.statsData = response.data.data
      }).catch(() => {
        this.$message.error('获取统计数据失败')
      })
    },
    // 安全配置功能
    handleSecurityConfig() {
      this.securityDialogVisible = true
      this.loadSecurityConfig()
    },
    loadSecurityConfig() {
      // 加载安全配置
      this.$http.get('/admin/security/config').then(response => {
        this.securityConfig = response.data.data || this.securityConfig
      }).catch(() => {
        this.$message.error('获取安全配置失败')
      })
    },
    saveSecurityConfig() {
      // 保存安全配置
      this.$http.post('/admin/security/config', this.securityConfig).then(response => {
        this.$message.success('安全配置保存成功')
        this.securityDialogVisible = false
      }).catch(() => {
        this.$message.error('保存安全配置失败')
      })
    },
    handleDeleteEachRow(row) {
      deleteGoods(row).then(response => {
        this.$notify.success({
          title: '成功',
          message: '删除成功'
        })
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['商品ID', '商品编号', '名称', '专柜价格', '当前价格', '是否新品', '是否热品', '是否在售', '首页主图', '宣传图片列表', '商品介绍', '详细介绍', '商品图片', '商品单位', '关键字', '类目ID', '品牌商ID']
        const filterVal = ['id', 'goodsSn', 'name', 'counterPrice', 'retailPrice', 'isNew', 'isHot', 'isOnSale', 'listPicUrl', 'gallery', 'brief', 'detail', 'picUrl', 'goodsUnit', 'keywords', 'categoryId', 'brandId']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '商品信息')
        this.downloadLoading = false
      })
    }
  }
}
</script>
